package com.ruoyi.student.controller;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.student.service.IStudentPhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 学生照片上传控制器
 * 处理照片上传和学生信息匹配
 */
@RestController
@RequestMapping("/student/photo")
public class StudentPhotoController extends BaseController {

    @Autowired
    private IStudentPhotoService studentPhotoService;

    @Value("${custom.student-photo-path}")
    private String studentPhotoPath;

    /**
     * 上传学生照片
     * 将照片保存到指定目录，不修改文件名
     */
/*    @PreAuthorize("@ss.hasPermi('student:info:edit')")*/
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public AjaxResult uploadFiles(@RequestParam("files") MultipartFile[] files) {
        try {
            // 上传文件并保存到指定目录
            System.out.println(files.length);
            int count = studentPhotoService.uploadPhotos(files, studentPhotoPath);
            return AjaxResult.success("文件上传成功，共 " + count + " 个文件");
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

    /**
     * 匹配学生照片
     * 根据文件名（学号）匹配学生信息并更新照片路径
     */
/*    @PreAuthorize("@ss.hasPermi('student:info:edit')")*/
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PostMapping("/match")
    public AjaxResult matchPhotos() {
        try {
            Map<String, Integer> result = studentPhotoService.matchAndUpdatePhotos(studentPhotoPath);
            return AjaxResult.success()
                    .put("data", new HashMap<String, Object>() {{
                        put("totalCount", result.get("totalCount"));
                        put("matchedCount", result.get("matchedCount"));
                        put("unmatchedCount", result.get("totalCount") - result.get("matchedCount"));
                    }});
        } catch (Exception e) {
            return AjaxResult.error("匹配失败: " + e.getMessage());
        }
    }
}

